package com.guiji.quartz.domain;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.quartz.config.ProxyConfig;
import com.guiji.quartz.task.DataSaveUtil;
import com.guiji.quartz.util.DelPicUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description: 需要代理
 * @author: wangxw
 * @date 2021/12/3 11:38
 */
public class Theathletic {
	private static final Logger log = LoggerFactory.getLogger(Theathletic.class);

	static {
		System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
	}

	public static void mainMethod() throws Exception {

		HttpResponse response = null;
		String baseUrl = "https://theathletic.com/";
		try {
			response = HttpRequest.get(baseUrl)
				.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
				.header("Accept-Encoding", "gzip, deflate")
				.setHttpProxy(ProxyConfig.url, ProxyConfig.ip)
				.setConnectionTimeout(30000)
				.execute();

			if (null != response && response.getStatus() == 200) {
				List<HttpCookie> cookies = response.getCookies();
				String resp = response.body();
				Set<String> resUrl = getUrl(resp);
				getContent(resUrl, cookies);
			} else {
				log.error(baseUrl + String.valueOf(response.getStatus()));
			}

		} catch (Exception e) {
			log.error(String.format("访问 {} 失败", baseUrl) + e);
			return;
		}
	}


	private static void getContent(Set<String> listContent, List<HttpCookie> cookies) throws MalformedURLException, URISyntaxException, InterruptedException {
		for (String url : listContent) {
			Thread.sleep(1000);
			if (!url.startsWith("https")) {
				url = new StringBuffer("https://theathletic.com").append(url).toString();
			}
			if (null != cookies && cookies.size() > 0) {
				CookieManager ccm = new CookieManager();
				CookieStore CookieStore = ccm.getCookieStore();
				for (HttpCookie cookie : cookies) {
					URL domain = new URL("https://theathletic.com");
					CookieStore.add(domain.toURI(), cookie);
				}
				HttpRequest.setCookieManager(ccm);
			}

//			url = "https://theathletic.com/2971774/2021/11/26/one-black-friday-free-agent-deal-for-every-mlb-team-to-make-before-baseballs-likely-work-stoppage/";
			log.info("getContent执行到-{},listContent长度-{}", url, listContent.size());
			String doc;
			JXDocument jxDocument;
			try {
				HttpResponse response = HttpRequest.get(url)
					.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36")
					.header("Refer", "https://theathletic.com/")
					.setHttpProxy(ProxyConfig.url, ProxyConfig.ip)
					.setConnectionTimeout(30000).execute();

				if (response.getStatus() == 301 || response.getStatus() == 302) {
					String redirectUrl2 = response.headers().get("Location").get(0);
					HttpResponse responseRR = HttpRequest.get(redirectUrl2)
						.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36")
						.header("Refer", url)
//						.setHttpProxy(ProxyConfig.url, ProxyConfig.ip)
						.setConnectionTimeout(30000).execute();
					if (responseRR.getStatus() == 200) {
						doc = responseRR.body();
					} else {
						log.error("redirect error");
						continue;
					}

				} else if (response.getStatus() == 200) {
					doc = response.body();
				} else {
					log.error("unexpected status");
					continue;
				}


				jxDocument = new JXDocument(doc);
			} catch (Exception e) {
				log.info("代理失败2" + e);
				continue;
			}
			String title = null;
			try {
				title = (String) jxDocument.sel("//h1//text()").get(0);
			} catch (Exception e) {
				log.error("标题错误-------------" + url + "-------------------标题错误");
				continue;
			}
			StringBuffer content = new StringBuffer();
			String contentStr = null;
			try {

				Document document = Jsoup.parse(doc);
				Element mainArea = document.getElementById("newsLede");
				if (mainArea == null) {
					mainArea = document.getElementById("the_paywall");
					mainArea.select("a").remove();
					contentStr =mainArea.toString().replaceAll("<br>","\\$\\$\\$").replaceAll("\n","").replaceAll("</p>", "\\$\\$\\$").replaceAll("<figcaption.*?</figcaption>", "")
						.replaceAll("</ul>.*?\n", "\\$\\$\\$")
						.replaceAll("</li>.*?\n", "\\$\\$\\$")
						.replaceAll("\n", "")
						.replaceAll("<(.|\n)*?>", " ");


				}else {

					Elements pElements = mainArea.select("P");
					if (null != pElements && pElements.size() > 0) {
						for (Element pdom : pElements) {
							String temp = pdom.text();
							if (null != temp && !temp.toString().contains("Your support through more subscriptions can help us") && !temp.toString().contains("Only the headline and picture of this report")) {
								content.append(temp + "$$$");
								pdom.remove();
							}
						}
					}
					contentStr = content.toString();
				}

			} catch (Exception e) {
				continue;
			}

			List<Object> srcImgs = new ArrayList<>();
			List<String> newImgs = new ArrayList<>();
			String img = null;
			try {
				String imgXpath = "//div[@class='news-item-styles__ImageContainer-sc-t7hm2p-1 huXhUI']//img/@src";
				int imgSize = jxDocument.sel(imgXpath).size();
				if(imgSize==0){
					imgXpath ="//div[@class='article-image-container article-main-image margin-bottom-20-large']//img/@src";
					imgSize = jxDocument.sel(imgXpath).size();
				}
				if (imgSize > 0) {
					String temp = null;
					for (int k = 0; k < imgSize; k++) {
						temp = jxDocument.sel(imgXpath).get(k).toString();
						img = temp.strip();
						srcImgs.add(img);
						break;
					}
				}

			} catch (Exception e) {
				log.error("可能没有图片");
				img = "";
			} finally {
				if (srcImgs.size() > 0) {
					newImgs = DelPicUtil.delPic(srcImgs);
				}
			}

			Date date = new Date();
			if (contentStr.length() > 50000 || contentStr.replaceAll("\\$|[\\s\\p{Zs}]", "").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				System.out.println("=======================================================");
				System.out.println(url);
				System.out.println(title);

				for (Object imgitem : srcImgs) {
					System.out.println(" " + imgitem);
				}
				System.out.println(contentStr);
				System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
				DataSaveUtil.saveData(title, contentStr, newImgs, url, date, "https://theathletic.com/", "Theathletic-Sports");
				log.info(Thread.currentThread().getName() + "-----------------Theathletic-Sports ----------------");
			} catch (Exception e) {
				continue;
			}

		}
	}

	private static Set<String> getUrl(String content) {
		Set<String> res = new HashSet<>();
		String pattern = "https://theathletic.com/.*?/.*?/.*?";
		Pattern p = Pattern.compile(pattern);


		JXDocument jxDocument = new JXDocument(content);
		int imgSize = 0;
		try {
			imgSize = jxDocument.sel("//a/@href").size();
			if (imgSize > 0) {

				for (int k = 0; k < imgSize; k++) {
					String temp = null;
					temp = jxDocument.sel("//a/@href").get(k).toString();
					temp = temp.strip();
					if (temp.contains("-")) {
						Matcher m = p.matcher(temp);
						while (m.find()) {
							res.add(temp);
						}

					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return res;
	}


//	public static void main(String[] args) throws Exception {
//		mainMethod();
//	}

}



